package socket.test1Base;

import org.junit.Test;

import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * Created by majian8 on 2019/6/25.
 */
public class Test3URLConnection {


    /**
     * URLConnection没有公开的构造方法，
     * 这意味着无法直接获取URLConnection
     * 一般是从 Url.openConnection()获取
     */
    @Test
    public void test1(){
        try {
            URL u1=new URL("http://www.baidu.com");
            URLConnection connection=u1.openConnection();
            System.out.println("contentType: "+connection.getContentType());
            System.out.println("contentLength: "+connection.getContentLength());
            System.out.println("date: "+connection.getDate());
            //获取任意header
            System.out.println("header: "+connection.getHeaderField("Content-length"));
            //返回第n个header
            System.out.println("header-n: "+connection.getHeaderFieldKey(2));



        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * urlconnection 缓存
     * responseCache
     * cacheRequest
     * cacheResponse
     */
    @Test
    public void test2() throws Exception {
        URL u1=new URL("http://www.baidu.com");
        URLConnection connection=u1.openConnection();
        //不使用缓存
        connection.setUseCaches(false);
        //不仅可以读，还可以写
        connection.setDoOutput(true);
        //socket 1000毫秒
        connection.setConnectTimeout(1000);
        //从流中读取的时间 1000毫秒
        connection.setReadTimeout(1000);


        //从连接中获取url
        URL u2=connection.getURL();
    }

    /**
     * cookie ，header
     */
    @Test
    public void test3() throws Exception {
        URL url=new URL("http://www.baidu.com");
        URLConnection con=url.openConnection();
        con.setRequestProperty("Cookie","username=zhangsan;password=lisi");
        //增加一个header
        con.addRequestProperty("abd","234");
        // 获取所有请求属性
        Map<String,List<String>> map=con.getRequestProperties();
    }


    /**
     * 请求（还有httpurlconnection）
     */
    @Test
    public void test4() throws IOException {
        URL url=new URL("http://www.baidu.com");
        URLConnection con=url.openConnection();
        //请求方法将由 get 转为 post
        con.setDoOutput(true);
        OutputStream os=con.getOutputStream();

    }


    @Test
    public void test(){

    }


}
